<template>
  <el-card>
    <div slot="header">
      <span>添加问卷</span>
    </div>
    <el-form :model="form" ref="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-select v-model="form.class_id" placeholder="请选择班级">
          <el-option
            v-for="cls in classes"
            :key="cls.id+'cls'"
            :label="cls.class_name"
            :value="cls.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选项管理">
        <el-select v-model="form.item" placeholder="请选择">
          <el-option
            v-for="itm in items"
            :key="itm.id+'cls'"
            :label="itm.item_name"
            :value="itm.children"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="大纲">
        <el-tree
          :render-after-expand="false"
          @check-change="checkChange"
          show-checkbox
          :data="outlines"
          :props="outlinesProps"
        ></el-tree>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">添加</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      classes: [],
      outlines: [],
      items: [],
      outlinesProps: {
        children: "children",
        label: "outline_name"
      },

      form: {
        title: "",
        item: "",
        outlines: []
      }
    };
  },
  created() {
    this.getClasses();
    this.getItems();
    this.getOutlines();
  },
  methods: {
    async save() {
      await this.axios({
        method: "post",
        url: "/papers/add",
        data: {
          title: this.form.title,
          content: JSON.stringify(this.form.outlines),
          class_id: this.form.class_id,
          item: JSON.stringify(this.form.item)
        }
      });
      this.$message.success("添加成功");
         this.$router.push({
          name:'HomePapers'
      })
    },
    checkChange(node, flag) {
      if (node.children.length == 0) {
        if (flag == true) {
          this.form.outlines.push(node);
        } else {
          const pos = this.form.outlines.indexOf(node);
          this.form.outlines.splice(pos, 1);
        }
      }
    },
    async getOutlines() {
      const {
        data: { data }
      } = await this.axios({
        url: "/outlines"
      });
      this.outlines = data;
    },
    async getClasses() {
      const {
        data: {
          data: { rows }
        }
      } = await this.axios({
        url: "/classes"
      });
      this.classes = rows;
    },
    async getItems() {
      const {
        data: { data }
      } = await this.axios({
        url: "/items"
      });
      this.items = data;
    }
  }
};
</script>
